var mysql = require('mysql');
var pool = mysql.createPool({
    host: 'localhost',
    user: 'root',
    password: 'chenyuzhen',
    database: 'it_mobile'
})

/**
 * 查询值
 * @param {表名} tablename 
 * @param {列名} col 
 * @param {值} val 
 * @param {回调函数} callback 
 */
function query (tablename, col, val, callback) {
    pool.getConnection(function(err, connection) {
        if(err) {
            callback(err);
        } else {
            let sql = "select * from " + tablename + " where " + col + '="' + val + '"';
            console.log(sql)
            connection.query(sql, function(err1, rows) {
                callback( err1, rows);
                connection.release();
            })
        }
    })
}

/**
 * 插入值
 * @param {表名} tableName 
 * @param {列名} cols 
 * @param {对应的每一列的数据} data 
 * @param {执行完成的回调函数} callback 
 */
function insert(tableName, cols, data, callback ) {
    pool.getConnection(function(err, connection) {
        if(err) {
            callback(err);  
        } else {
            let sql = "INSERT INTO " + tableName + " (" + cols + ")" + " values (" + data + ")";
            console.log(sql)
            connection.query(sql, function(err1, rows) {
                callback(err1, rows);
                connection.release();
            })
        }
    })
}

/**
 * 执行sql语句
 * @param {*} sql 
 * @param {*} callback 
 */
function execute( sql, callback ) {
    pool.getConnection(function(err, connection) {
        if(err) {
            callback(err);  
        } else {
            connection.query(sql, function(err1, rows) {
                callback(err1, rows);
                connection.release();
            })
        }
    })
}

/**
 * 修改设备状态
 * @param {*} sql 
 * @param {*} callback 
 */
function changeState( id, state, callback ) {
    pool.getConnection(function(err, connection) {
        if(err) {
            callback(err);  
        } else {
            var sql = "UPDATE equipmentinfo SET state='" + state + "' WHERE id='" + id + "'";
            console.log(sql);
            connection.query(sql, function(err1, rows) {
                callback(err1, rows);
                connection.release();
            })
        }
    })
}
exports.query = query;
exports.insert = insert;
exports.execute = execute;
exports.changeState = changeState;